# -*- coding:UTF8 -*-
# author:叶向平
# date:2020/4/5
# IDE:PyCharm

import requests
from json import JSONDecoder
import cv2
import time
import threading
from POST请求 import post

# 开启摄像头
cap = cv2.VideoCapture('rtsp://admin:725123abcD@192.168.1.64:554/Streaming/Channels/1')

# Face++官方接口封装
def compareIm(faceId1, faceId2):
    # 传送两个本地图片地址 例如："D:/Downloads/wt.jpg"
    try:
        # 官方给你的接口地址
        compare_url = "https://api-cn.faceplusplus.com/facepp/v3/compare"
        # 创建应用分配的key和secret
        key = "xuyvjPVWjgOYApc-C4z7EZk_rXaARyzB"
        secret = "d8E0AseQGfbre-WIZlcSjpuYI5mMbTqo"
        # 创建请求数据
        data = {"api_key": key, "api_secret": secret}
        files = {"image_file1": open(faceId1, "rb"), "image_file2": open(faceId2, "rb")}
        # 通过接口发送请求
        response = requests.post(compare_url, data=data, files=files)

        req_con = response.content.decode('utf-8')
        req_dict = JSONDecoder().decode(req_con)
        # print(req_dict)
        # 获得json文件里的confidence值，也就是相似度
        confindence = req_dict['confidence']
        # s1 = unicode('xiangsidu', 'utf-8')
        print('相似度:',confindence)
        if confindence > 70:
            print("请摇摇头！！！")
        return confindence
    except Exception:
        pass
    # print("无法识别！")


def sbdg(i):
    while True:
        try:
            if compareIm(imgdict[i], "./img/now.jpg") > 75 and post():
                print("确认:%s\n" % i)
                imgdict_1[i] = 1
            else:
                print("非活体攻击！\n")
        except Exception:
            pass
        time.sleep(2)


# 该函数用于不断捕捉摄像头，并保存图片
def getimg():
    while (cap.isOpened()):
        # 读取帧摄像头
        ret, frame = cap.read()
        if ret == True:
            # 输出当前帧
            # out.write(frame)
            cv2.imwrite('./img/now.jpg', frame)
            cv2.imshow('实时录入脸部', frame)
            cv2.resizeWindow("实时录入脸部", 640, 480)

            # 键盘按 Q 退出
            if cv2.waitKey(1) == ord('q'):
                flag = 1
                print('********************************************')
                print("未到人员：",end='')
                for i in imgdict_1:
                    if imgdict_1[i] == 0:
                        flag = 0
                        print(i,end=' ')
                print()
                if flag:
                    print(0)
                print('********************************************')
                print()
                break
        else:
            break


imgdict = {"叶向平": "./img/yxp.jpg", "李璇": "/img/shezhang1.jpg", "老人": "/img/1.jpg", "徐龙跃": "/img/xly.jpg", "时义栋": "/img/xyd.jpg"}
imgdict_1 = {"叶向平": 0, "李璇": 0, "老人": 0, "徐龙跃": 0, "时义栋": 0}


def start():
    # 开启捕捉摄像头进程
    threading.Thread(target=getimg).start()
    # 每个匹配对象创建一个线程，为了降低等待延迟
    for x in imgdict:
        threading.Thread(target=sbdg, args=(x,)).start()
